×
☰ See All Chapters

React Lists - Mapping Over Data to Create Elements

JSX is JavaScript, so you can incorporate JSX directly inside of JavaScript functions. You tried this a little already by passing functions to attributes. You also used variables to reuse data. Now it’s time to create JSX directly from data using standard JavaScript code. For example, you can map an array to JSX elements:

function FirstComponent() {

  const items = ['Pen', 'Book', 'Table', 'Board', 'Bottle'];

  return (

    <div>

      <ul>

        {items.map((item, i) => (

          <li key="{i}">{item}</li>

        ))}

      </ul>

    </div>

  )

}

 

export default FirstComponent;

react-mapping-over-data-to-create-elements-0
 

To do this, you’ll map over the data and return a JSX element. There are a few things you’ll need to keep in mind as you write the code.

  1. Group of items needs to be surrounded by a container <div> 

  2. Every item needs a special property called key. The key needs to be a unique piece of data that React can use to keep track of the elements so it can know when to update the component. The key will be stripped out of the compiled HTML, since it is for internal purposes only. Whenever you are working with loops you will need to add a simple string as a key. 

The resulting HTML for above component would look like this:

        <div>

                <ul>

                        <li>Pen</li>

                        <li>Book</li>

                        <li>Table</li>

                        <li>Board</li>

                        <li>Bottle</li>

                </ul>

        </div>

Below we have another example of mapping an array objects to JSX elements:

function FirstComponent() {

  const ietms = [

    {

      name: 'Pen',

      price: "10$"

    },

    {

      name: 'Book',

      price: "12$"

    },

    {

      name: 'Table',

      price: "15$"

    }

  ];

  return (

    <div>

      <ul>

        {

          ietms.map(ietm => (

            <li key={ietm.name}>

              Name: <span id={ietm.name}>{ietm.name}</span> &nbsp;

              Price: <span id={ietm.price}>{ietm.price}</span>

            </li>

          ))

        }

      </ul>

    </div>

 

  )

}

 

export default FirstComponent;

react-mapping-over-data-to-create-elements-1
 

All Chapters
Author